<template>
  <div class="p-6 space-y-4">
    <!-- 顶部工具条 -->
    <el-card shadow="never">
      <div class="toolbar">
        <el-form :inline="true" :model="filters" class="filters">
          <el-form-item label="工卡号">
            <el-input
              v-model="filters.cardId"
              clearable
              placeholder="输入工卡号"
              @keyup.enter.native="loadData"
            />
          </el-form-item>
          <el-form-item label="客户代码">
            <el-input
              v-model="filters.customerCode"
              clearable
              placeholder="上海客户代码"
              @keyup.enter.native="loadData"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="filters.status"
              clearable
              placeholder="是否报客户"
              style="width: 100px"
            >
              <el-option label="已报" value="1" />
              <el-option label="未报" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="责任人">
            <el-select
              v-model="filters.ownerName"
              placeholder="选择负责人"
              clearable
              filterable
            >
              <el-option
                v-for="item in ownerList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="PTE反馈超期状态">
            <el-select
              v-model="filters.pteStatus"
              clearable
              placeholder="PTE反馈超期状态"
              style="width: 100px"
            >
              <el-option label="超期" value="1" />
              <el-option label="未超期" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户回复超期状态">
            <el-select
              v-model="filters.custStatus"
              clearable
              placeholder="客户回复超期状态"
              style="width: 100px"
            >
              <el-option label="超期" value="1" />
              <el-option label="未超期" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="晶圆批次">
            <el-input
              v-model="filters.wfLot"
              clearable
              placeholder="输入晶圆批次"
              @keyup.enter.native="loadData"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="loadData"
              >查询</el-button
            >
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button plain :loading="loading" @click="refresh"
              >刷新</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              plain
              :loading="loading"
              type="warning"
              @click="handleExport"
              >导出历史记录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 主表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>Hold Lot 列表</span>
          <div class="header-actions">
            <el-text type="info">共 {{ pagination.total }} 条</el-text>
          </div>
        </div>
      </template>

      <el-table
        :data="rows"
        v-loading="loading"
        border
        height="62vh"
        row-key="keyId"
      >
        <el-table-column type="index" width="60" label="#" />
        <el-table-column prop="cardId" label="工卡号" min-width="160" sortable>
          <template #default="{ row }">
            <el-text class="font-mono">{{ row.cardId }}</el-text>
          </template>
        </el-table-column>
        <el-table-column
          prop="custCode"
          label="上海客户代码"
          min-width="120"
          sortable
        />
        <el-table-column
          prop="groupCust"
          label="集团客户代码"
          min-width="140"
          sortable
        />
        <el-table-column
          prop="productNo"
          label="产品型号"
          min-width="140"
          sortable
        />
        <el-table-column
          prop="custLotId"
          label="晶圆批次"
          min-width="140"
          sortable
        />
        <el-table-column
          prop="currentQty"
          label="工单数量"
          width="100"
          sortable
        />
        <el-table-column
          prop="holdDays"
          label="扣押时长(天)"
          width="120"
          sortable
        />
        <el-table-column
          prop="shelfLabel"
          label="储位号"
          width="100"
          sortable
        />
        <el-table-column
          prop="holdDate"
          label="扣押时间"
          min-width="170"
          sortable
        >
          <template #default="{ row }">{{ formatDate(row.holdDate) }}</template>
        </el-table-column>
        <el-table-column prop="status" label="当前状态" width="110" sortable>
          <template #default="{ row }">
            <el-tag>{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="opCode"
          label="当前站点"
          min-width="140"
          sortable
        />
        <el-table-column prop="dept" label="处置部门" width="100" sortable />
        <el-table-column
          prop="ownerName"
          label="工单负责人"
          width="120"
          sortable
        />
        <el-table-column label="反馈进度" min-width="220" sortable>
          <template #default="{ row }">
            <div class="flex items-center gap-2">
              <el-tag v-if="row.reportedAt" type="success" effect="light"
                >已报客户：{{ formatDateTime(row.reportedAt) }}</el-tag
              >
              <el-tag v-else type="warning" effect="plain">未报</el-tag>
              <el-tag v-if="row.customerRepliedAt" type="info" effect="light"
                >客户回复：{{ formatDateTime(row.customerRepliedAt) }}</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="pteFeedbackHours"
          label="PTE反馈(时)"
          width="100"
          sortable
        />
        <el-table-column
          prop="custFeedbackHours"
          label="客户回复(时)"
          width="100"
          sortable
        />
        <el-table-column prop="remark" label="备注" width="100" sortable />
        <el-table-column
          prop="isRecycled"
          label="是否需要回收"
          width="100"
          sortable
        />
        <el-table-column label="操作" fixed="right" width="320">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              plain
              :disabled="row.reportedAt"
              @click="openReport(row)"
              >报客户</el-button
            >
            <el-button
              size="small"
              type="success"
              plain
              :disabled="!row.reportedAt"
              @click="openReply(row)"
              >记录回复</el-button
            >
            <el-button size="small" @click="openDetail(row)">详情</el-button>

            <el-button size="small" type="info" @click="openRemarkDialog(row)"
              >备注</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-4 flex justify-between items-center">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, sizes, total"
          :total="pagination.total"
          :page-size="pagination.size"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="onPageChange"
          @size-change="onSizeChange"
        />
      </div>
    </el-card>

    <!-- 报客户对话框 -->
    <el-dialog
      v-model="reportDialog.visible"
      title="报客户"
      width="560px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="reportFormRef"
        :model="reportDialog.form"
        :rules="reportRules"
        label-width="90px"
      >
        <el-form-item label="工卡号">
          <el-input v-model="reportDialog.form.cardId" disabled />
        </el-form-item>
        <el-form-item label="负责人姓名" prop="ownerName">
          <el-input v-model="reportDialog.form.ownerName" disabled />
        </el-form-item>
        <el-form-item label="报出时间" prop="reportedAt">
          <el-date-picker
            v-model="reportDialog.form.reportedAt"
            type="datetime"
            placeholder="选择时间"
            :default-time="defaultTime"
            :shortcuts="dateShortcuts"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="报出方式" prop="channel">
          <el-select
            v-model="reportDialog.form.channel"
            placeholder="选择报出方式"
          >
            <el-option label="邮件" value="email" />
            <el-option label="电话" value="phone" />
            <el-option label="IM/群" value="im" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="reportDialog.form.remark"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reportDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="saving.report" @click="submitReport"
          >保存</el-button
        >
      </template>
    </el-dialog>

    <!-- 客户回复对话框 -->
    <el-dialog
      v-model="replyDialog.visible"
      title="记录客户回复"
      width="640px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="replyFormRef"
        :model="replyDialog.form"
        :rules="replyRules"
        label-width="100px"
      >
        <el-form-item label="工卡号">
          <el-input v-model="replyDialog.form.cardId" disabled />
        </el-form-item>
        <el-form-item label="负责人姓名">
          <el-input v-model="replyDialog.form.ownerName" disabled />
        </el-form-item>
        <el-form-item label="回复时间" prop="customerRepliedAt">
          <el-date-picker
            v-model="replyDialog.form.customerRepliedAt"
            type="datetime"
            placeholder="选择时间"
            :default-time="defaultTime"
            :shortcuts="dateShortcuts"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="回复内容" prop="replyContent">
          <el-input
            v-model="replyDialog.form.replyContent"
            type="textarea"
            :rows="5"
            maxlength="2000"
            show-word-limit
            placeholder="粘贴或录入客户反馈…"
          />
        </el-form-item>
        <el-form-item label="下一步建议">
          <el-input
            v-model="replyDialog.form.suggest"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="replyDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="saving.reply" @click="submitReply"
          >保存</el-button
        >
      </template>
    </el-dialog>

    <!-- 详情侧抽屉 -->
    <el-drawer
      v-model="detail.visible"
      :title="`工卡详情 - ${detail.row?.cardId || ''}`"
      size="50%"
    >
      <el-descriptions border :column="2" v-if="detail.row">
        <el-descriptions-item label="工卡号">{{
          detail.row.cardId
        }}</el-descriptions-item>
        <el-descriptions-item label="状态"
          ><el-tag>{{ detail.row.status }}</el-tag></el-descriptions-item
        >
        <el-descriptions-item label="客户(上/集)"
          >{{ detail.row.custCode }} /
          {{ detail.row.groupCust }}</el-descriptions-item
        >
        <el-descriptions-item label="产品型号">{{
          detail.row.productNo
        }}</el-descriptions-item>
        <el-descriptions-item label="晶圆批次">{{
          detail.row.custLotId
        }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{
          detail.row.currentQty
        }}</el-descriptions-item>
        <el-descriptions-item label="扣押时长">{{
          detail.row.holdDays
        }}</el-descriptions-item>
        <el-descriptions-item label="储位号">{{
          detail.row.shelfLabel
        }}</el-descriptions-item>
        <el-descriptions-item label="扣押时间">{{
          formatDateTime(detail.row.holdDate)
        }}</el-descriptions-item>
        <el-descriptions-item label="站点">{{
          detail.row.opCode
        }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{
          detail.row.dept
        }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{
          detail.row.ownerName
        }}</el-descriptions-item>
        <el-descriptions-item label="负责人反馈用时(小时)">
          {{
            calcFeedbackHours(detail.row?.holdDate, detail.row?.reportedAt) ??
            "—"
          }}
        </el-descriptions-item>
        <el-descriptions-item label="客户反馈用时(小时)">
          {{
            calcFeedbackHours(
              detail.row?.reportedAt,
              detail.row?.customerRepliedAt
            ) ?? "—"
          }}
        </el-descriptions-item>
      </el-descriptions>
      <el-divider />
      <el-timeline>
        <el-timeline-item
          v-if="detail.row?.reportedAt"
          :timestamp="formatDateTime(detail.row!.reportedAt)"
          type="success"
          >工程师已报客户（{{ detail.row?.channelLabel || "—" }}）
          <el-text type="info" style="margin-left: 8px">
            用时：{{
              calcFeedbackHours(detail.row?.holdDate, detail.row?.reportedAt) ??
              "—"
            }}
            小时
          </el-text>
        </el-timeline-item>
        <el-timeline-item
          v-if="detail.row?.customerRepliedAt"
          :timestamp="formatDateTime(detail.row!.customerRepliedAt)"
          type="success"
        >
          <div class="space-y-1">
            <div>客户回复</div>
            <el-text>{{ detail.row?.replyContent }}</el-text>
            <el-text type="info" style="margin-top: 4px">
              用时：{{
                calcFeedbackHours(
                  detail.row?.reportedAt,
                  detail.row?.customerRepliedAt
                ) ?? "—"
              }}
              小时
            </el-text>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>

    <!-- 备注对话框 -->
    <el-dialog
      v-model="remarkDialog.visible"
      title="添加备注"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="remarkDialog.form"
        label-width="100px"
        ref="remarkFormRef"
      >
        <el-form-item label="工卡号">
          <el-input v-model="remarkDialog.form.cardId" disabled />
        </el-form-item>
        <el-form-item label="是否需要回收">
          <el-radio-group v-model="remarkDialog.form.isRecycled">
            <el-radio :value="true">需要回收</el-radio>
            <el-radio :value="false">不需要回收</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="remarkDialog.form.remark"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
            placeholder="请输入备注内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="remarkDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveRemark">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import axios from "axios";

/** —— 类型定义 —— */
interface HoldLotRow {
  keyId: string; // 唯一键（建议用 ORDER_NO||'.'||SUB）
  cardId: string; // 工卡号（ORDER_NO||'.'||ORDER_SUB_LOT）
  custCode: string; // 上海客户代码
  groupCust: string; // 集团客户代码
  productNo: string; // 产品型号
  custLotId: string; // 晶圆批次
  currentQty: number; // 工单数量
  holdDays: number | null; // 扣押时长
  shelfLabel: string | null; // 储位号
  holdDate: string | null; // 扣押时间 ISO 字符串
  status: "HELD" | "RHLD" | "THLD" | string; // 当前状态
  opCode: string; // 当前站点
  dept: string; // 处置部门
  ownerName: string; // 工单负责人

  // 反馈字段（来自你们自己的业务表）
  reportedAt?: string | null; // 工程师报客户时间 ISO
  channel?: "email" | "phone" | "im" | "other" | null; // 报出方式
  channelLabel?: string | null; // 展示用
  remark?: string | null; // 备注
  customerRepliedAt?: string | null; // 客户回复时间
  replyContent?: string | null; // 客户回复内容
  suggest?: string | null; // 下一步建议
}

/** —— 过滤、分页、排序 —— */
const filters = reactive({
  cardId: "",
  wfLot: "",
  customerCode: "",
  pteStatus: "",
  custStatus: "",
  ownerName: "",
  status: ""
});
const pagination = reactive({ page: 1, size: 20, total: 0 });

// 责任人列表
const ownerList = [
  "董小勇",
  "朱俊",
  "李明珠",
  "居校红",
  "张瑞杨",
  "赵宏锐",
  "刘浩",
  "朱思腾",
  "胡金涛",
  "黄嘉辰",
  "崔佳庆",
  "孙娜",
  "伍海龙",
  "杨振宁",
  "詹锦琦",
  "卞豆豆",
  "李唐洋",
  "严正江",
  "无"
];

const rows = ref<HoldLotRow[]>([]);
const loading = ref(false);

// const API_HOLD_LOTS_EXPORT =
// "https://localhost:44389/api/shipment/feedback/export";
const API_HOLD_LOTS_EXPORT =
  "http://10.0.8.42:8089/api/shipment/feedback/export";

/** —— 对话框状态 —— */
const reportDialog = reactive({
  visible: false,
  form: {
    cardId: "",
    reportedAt: "",
    ownerName: "",
    channel: "email" as "email" | "phone" | "im" | "other",
    remark: "",
    holdDate: "",
    opCode: "",
    productNo: "",
    custLotId: ""
  }
});
const replyDialog = reactive({
  visible: false,
  form: {
    cardId: "",
    ownerName: "",
    customerRepliedAt: "",
    replyContent: "",
    suggest: "",
    opCode: ""
  }
});
const detail = reactive<{ visible: boolean; row: HoldLotRow | null }>({
  visible: false,
  row: null
});
const saving = reactive({ report: false, reply: false });

const dateShortcuts = [
  { text: "此刻", value: () => new Date() },
  { text: "5 分钟前", value: () => new Date(Date.now() - 5 * 60 * 1000) },
  { text: "1 小时前", value: () => new Date(Date.now() - 60 * 60 * 1000) }
];
const defaultTime = new Date();

/** —— 校验规则 —— */
const reportFormRef = ref<FormInstance>();
const replyFormRef = ref<FormInstance>();
const reportRules: FormRules = {
  reportedAt: [
    { required: true, message: "请选择报出时间", trigger: "change" }
  ],
  channel: [{ required: true, message: "请选择报出方式", trigger: "change" }]
};
const replyRules: FormRules = {
  customerRepliedAt: [
    { required: true, message: "请选择客户回复时间", trigger: "change" }
  ],
  replyContent: [{ required: true, message: "请输入回复内容", trigger: "blur" }]
};

/** —— 工具函数 —— */
function formatDate(d?: string | null) {
  if (!d) return "—";
  const dt = new Date(d);
  if (Number.isNaN(dt.getTime())) return d;
  return dt.toLocaleDateString();
}
function calcFeedbackHours(
  holdDate?: string | Date | null,
  reportedAt?: string | Date | null
) {
  if (!holdDate || !reportedAt) return null;
  const h = new Date(holdDate).getTime();
  const r = new Date(reportedAt).getTime();
  if (isNaN(h) || isNaN(r)) return null;
  const hours = (r - h) / (1000 * 60 * 60);
  return Number.isFinite(hours) ? Number(hours.toFixed(1)) : null;
}
function formatDateTime(d?: string | null) {
  if (!d) return "—";
  const dt = new Date(d);
  if (Number.isNaN(dt.getTime())) return d;
  return dt.toLocaleString();
}

/** —— API 占位 ——
 * 你需要把下面的 fetch/post 调整为你们的后台接口：
 *   - /api/hold-lots    GET 按视图分页查询
 *   - /api/feedback/report  POST 记录报客户
 *   - /api/feedback/reply   POST 记录客户回复
 */
// const API_HOLD_LOTS = "https://localhost:44389/api/shipment/getHoldLot";
const API_HOLD_LOTS = "http://10.0.8.42:8089/api/shipment/getHoldLot";
async function apiFetchHoldLots(
  params: any
): Promise<{ records: HoldLotRow[]; total: number }> {
  // TODO: 替换为真实 API。这里返回模拟数据结构，以便你可以先联调前端。
  // 约定：视图字段映射到前端字段在 transform 内处理。
  const { data } = await axios.get(API_HOLD_LOTS, { params });
  return {
    records: data.records,
    total: data.total
  };
}
// const API_HOLD_LOTS_REPORT =
// "https://localhost:44389/api/shipment/feedback/report";
const API_HOLD_LOTS_REPORT =
  "http://10.0.8.42:8089/api/shipment/feedback/report";
async function apiPostReport(payload: {
  cardId: string;
  ownerName: string;
  reportedAt: string;
  channel: string;
  remark?: string;
  holdDate: string;
  opCode: string;
  productNo: string;
  custLotId: string;
}) {
  const { data } = await axios.post(API_HOLD_LOTS_REPORT, payload);
  return data;
}

// const API_HOLD_LOTS_REPLY =
// "https://localhost:44389/api/shipment/feedback/reply";
const API_HOLD_LOTS_REPLY = "http://10.0.8.42:8089/api/shipment/feedback/reply";
async function apiPostReply(payload: {
  cardId: string;
  customerRepliedAt: string;
  ownerName: string;
  replyContent: string;
  suggest?: string;
  opCode: string;
}) {
  const { data } = await axios.post(API_HOLD_LOTS_REPLY, payload);
  return data;
}

const API_HOLD_LOTS_REMARK =
  "http://10.0.8.42:8089/api/shipment/feedback/remark";
// const API_HOLD_LOTS_REMARK =
// "https://localhost:44389/api/shipment/feedback/remark";

async function apiGetRemark(params: {
  cardId: string;
  remark: string;
  isRecycled: boolean;
  opCode: string;
}) {
  try {
    const { data } = await axios.get(API_HOLD_LOTS_REMARK, { params });
    return data;
  } catch (error) {
    ElMessage.error("Error updating remark:", error);
  }
}

/** —— 数据加载 —— */
async function loadData() {
  loading.value = true;
  try {
    const res = await apiFetchHoldLots({
      page: pagination.page,
      pageSize: pagination.size,
      ...filters
    });
    rows.value = res.records;
    pagination.total = res.total;
  } catch (e: any) {
    ElMessage.error(e?.message || "加载失败");
  } finally {
    loading.value = false;
  }
}

function refresh() {
  loadData();
}

const handleExport = async () => {
  loading.value = true;
  try {
    const response = await axios.get(API_HOLD_LOTS_EXPORT, {
      params: {
        ...filters
      },
      responseType: "blob"
    });

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });

    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = `holdLot历史记录${new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "")}.xlsx`;
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    ElMessage.error(
      error?.response?.data?.message ||
        error?.message ||
        "获取数据失败，请检查接口状态"
    );
  } finally {
    loading.value = false;
  }
};

function resetFilters() {
  filters.cardId = "";
  filters.wfLot = "";
  filters.customerCode = "";
  filters.pteStatus = "";
  filters.custStatus = "";
  filters.ownerName = "";
  filters.status = "";
  pagination.page = 1;
  loadData();
}

function onPageChange(p: number) {
  pagination.page = p;
  loadData();
}
function onSizeChange(s: number) {
  pagination.size = s;
  pagination.page = 1;
  loadData();
}

/** —— 报客户 —— */
function openReport(row: HoldLotRow) {
  reportDialog.form.cardId = row.cardId;
  reportDialog.form.ownerName = row.ownerName;
  reportDialog.form.reportedAt = new Date().toISOString();
  reportDialog.form.channel = "email";
  reportDialog.form.remark = "";
  reportDialog.form.holdDate = row.holdDate;
  reportDialog.form.opCode = row.opCode;
  reportDialog.form.productNo = row.productNo;
  reportDialog.form.custLotId = row.custLotId;
  reportDialog.visible = true;
}

async function submitReport() {
  const form = reportFormRef.value;
  if (!form) return;
  await form.validate(async valid => {
    if (!valid) return;
    try {
      saving.report = true;
      await apiPostReport({
        cardId: reportDialog.form.cardId,
        ownerName: reportDialog.form.ownerName,
        reportedAt: reportDialog.form.reportedAt,
        channel: reportDialog.form.channel,
        remark: reportDialog.form.remark,
        holdDate: reportDialog.form.holdDate,
        opCode: reportDialog.form.opCode,
        productNo: reportDialog.form.productNo,
        custLotId: reportDialog.form.custLotId
      });
      // 前端乐观更新
      const target = rows.value.find(
        r => r.cardId === reportDialog.form.cardId
      );
      if (target) {
        target.reportedAt = reportDialog.form.reportedAt;
        target.channel = reportDialog.form.channel as any;
        target.channelLabel = {
          email: "邮件",
          phone: "电话",
          im: "微信/IM",
          other: "其他"
        }[reportDialog.form.channel];
        target.remark = reportDialog.form.remark;
      }
      ElMessage.success("已保存报客户时间");
      reportDialog.visible = false;
    } catch (e: any) {
      ElMessage.error(e?.message || "保存失败");
    } finally {
      saving.report = false;
    }
  });
}

/** —— 记录客户回复 —— */
function openReply(row: HoldLotRow) {
  if (!row.reportedAt) {
    ElMessage.warning("请先记录“报客户时间”");
    return;
  }
  replyDialog.form.cardId = row.cardId;
  replyDialog.form.ownerName = row.ownerName;
  replyDialog.form.customerRepliedAt = new Date().toISOString();
  replyDialog.form.replyContent = "";
  replyDialog.form.suggest = "";
  replyDialog.form.opCode = row.opCode;
  replyDialog.visible = true;
}

async function submitReply() {
  const form = replyFormRef.value;
  if (!form) return;
  await form.validate(async valid => {
    if (!valid) return;
    try {
      saving.reply = true;
      await apiPostReply({
        cardId: replyDialog.form.cardId,
        ownerName: replyDialog.form.ownerName,
        customerRepliedAt: replyDialog.form.customerRepliedAt,
        replyContent: replyDialog.form.replyContent,
        suggest: replyDialog.form.suggest,
        opCode: replyDialog.form.opCode
      });
      const target = rows.value.find(r => r.cardId === replyDialog.form.cardId);
      if (target) {
        target.customerRepliedAt = replyDialog.form.customerRepliedAt;
        target.replyContent = replyDialog.form.replyContent;
        target.suggest = replyDialog.form.suggest;
      }
      ElMessage.success("已保存客户回复");
      replyDialog.visible = false;
    } catch (e: any) {
      ElMessage.error(e?.message || "保存失败");
    } finally {
      saving.reply = false;
    }
  });
}

/** —— 详情 —— */
function openDetail(row: HoldLotRow) {
  detail.row = JSON.parse(JSON.stringify(row));
  detail.visible = true;
}

// 备注对话框相关的数据
const remarkDialog = ref({
  visible: false,
  form: {
    cardId: "",
    remark: "",
    isRecycled: false,
    opCode: ""
  }
});

// 打开备注对话框
const openRemarkDialog = row => {
  remarkDialog.value.form.cardId = row.cardId; // 将工卡号传递到对话框
  remarkDialog.value.form.remark = ""; // 如果有备注则显示，没有则为空
  remarkDialog.value.form.isRecycled = row.isRecycled == "N" ? false : true;
  remarkDialog.value.form.opCode = row.opCode;
  remarkDialog.value.visible = true; // 显示对话框
};

// 保存备注
const saveRemark = async () => {
  const { cardId, remark, isRecycled, opCode } = remarkDialog.value.form;
  ElMessage.success(`保存备注: ${remark} for cardId: ${cardId}`);

  try {
    // 调用更新 remark 接口
    const res = await apiGetRemark({
      cardId,
      remark,
      isRecycled,
      opCode
    });

    remarkDialog.value.visible = false;

    await loadData();
  } catch (error) {
    // 捕获并处理错误
    ElMessage.error(error?.message || "保存备注失败");
  }
};

onMounted(loadData);
</script>

<style scoped>
.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.filters {
  gap: 8px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.font-mono {
  font-family:
    ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
    "Courier New", monospace;
}
.mt-4 {
  margin-top: 1rem;
}
.flex {
  display: flex;
}
.items-center {
  align-items: center;
}
.justify-between {
  justify-content: space-between;
}
.gap-2 {
  gap: 0.5rem;
}
.space-y-1 {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}
.space-y-4 {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.p-6 {
  padding: 1.5rem;
}
</style>
